package edu.xidian.cnmano.util;

import edu.xidian.cnmano.entities.monitor.*;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.openapi.models.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author zhr 工具类，当使用java-client访问集群获取到node,pod,deployment信息时，需要将其转换成适合存取到数据库的Bean格式
 * @date 2020/11/28-11:01
 */
public class K8sElementInfoUtil {
    public static NodeInfo MetricsNodeToNodeInfo(MetricsNode metricsNode) {
        NodeInfo nodeInfo = new NodeInfo();
        nodeInfo.setNodeName(metricsNode.getMetadata().getName());
        nodeInfo.setUsedCpu(metricsNode.getUsage().getCpuInM().intValue());
        nodeInfo.setUsedMemory(metricsNode.getUsage().getMemoryInMi().intValue());
        nodeInfo.setReady(1);
        return nodeInfo;
    }

    public static NodeInfo V1NodeToNodeInfo(V1Node v1Node) {
        NodeInfo nodeInfo = new NodeInfo();
        nodeInfo.setNodeName(v1Node.getMetadata().getName());
        nodeInfo.setNodeIp(v1Node.getStatus().getAddresses().get(0).getAddress());
        nodeInfo.setTotalCpu(v1Node.getStatus().getAllocatable().get("cpu").getNumber().intValue() * 1000);
        nodeInfo.setTotalMemory(v1Node.getStatus().getAllocatable().get("memory").getNumber().divide(new BigDecimal(1048576)).intValue());
        nodeInfo.setMemoryPressure(v1Node.getStatus().getConditions().get(0).getStatus().equals("true") ? 1 : 0);
        nodeInfo.setDiskPressure(v1Node.getStatus().getConditions().get(1).getStatus().equals("true") ? 1 : 0);
        nodeInfo.setReady(v1Node.getStatus().getConditions().get(3).getStatus().equals("true") ? 1 : 0);
        return nodeInfo;
    }

    public static DeploymentInfo V1DeploymentToDeploymentInfo(V1Deployment v1Deployment) {
        DeploymentInfo deploymentInfo = new DeploymentInfo();
        deploymentInfo.setNamespace(v1Deployment.getMetadata().getNamespace());
        deploymentInfo.setDeploymentName(v1Deployment.getMetadata().getName());
        deploymentInfo.setTotalReplicas(v1Deployment.getSpec().getReplicas());
        deploymentInfo.setReadyReplicas(v1Deployment.getStatus().getReadyReplicas());
        return deploymentInfo;
    }

    public static PodInfo V1PodToPodInfo(V1Pod v1Pod) {
        PodInfo podInfo = new PodInfo();
        podInfo.setNamespace(v1Pod.getMetadata().getNamespace());
        String podName = v1Pod.getMetadata().getName();
        podInfo.setPodName(podName);
        podInfo.setDeployOnNodeName(v1Pod.getSpec().getNodeName());
        podInfo.setDeployOnNodeIp(v1Pod.getStatus().getHostIP());
        podInfo.setDeploymentName(extractDeploymentNameFromPodName(podName));
        Map<String, Quantity> requests = v1Pod.getSpec().getContainers().get(0).getResources().getRequests();
        if (requests != null) {
            if (requests.get("cpu") != null) {
                Float cpu = requests.get("cpu").getNumber().floatValue() * 1000;
                podInfo.setCpuRequest(cpu.intValue());
            }
            if (requests.get("memory") != null) {
                Long mem = requests.get("memory").getNumber().longValue() / 1048576;
                podInfo.setMemoryRequest(mem.intValue());
            }
        }
        podInfo.setPhase(v1Pod.getStatus().getPhase());
        return podInfo;
    }

    public static PodInfo MetricsPodToPodInfo(MetricsPod metricsPod) {
        PodInfo podInfo = new PodInfo();
        podInfo.setNamespace(metricsPod.getMetadata().getNamespace());
        podInfo.setPodName(metricsPod.getMetadata().getName());
        if(metricsPod.getContainers().size()!=0){
            podInfo.setCpuUsage(metricsPod.getContainers().get(0).getUsage().getCpuInM().intValue());
            podInfo.setMemoryUsage(metricsPod.getContainers().get(0).getUsage().getMemoryInMi().intValue());
        }
        return podInfo;
    }

    public static ServiceInfo V1ServiceToServiceInfo(V1Service v1Service) {
        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setNamespace(v1Service.getMetadata().getNamespace());
        serviceInfo.setServiceName(v1Service.getMetadata().getName());
        serviceInfo.setClusterIp(v1Service.getSpec().getClusterIP());
        serviceInfo.setType(v1Service.getSpec().getType());
        serviceInfo.setNamespace(v1Service.getMetadata().getNamespace());

        V1ServicePort v1ServicePort = v1Service.getSpec().getPorts().get(0);
        serviceInfo.setClusterPort(v1ServicePort.getPort());
        if (v1ServicePort.getTargetPort().isInteger()) {
            serviceInfo.setContainerPort(v1ServicePort.getTargetPort().getIntValue());
        }
        serviceInfo.setNodePort(v1ServicePort.getNodePort());

        return serviceInfo;
    }

    public static String extractDeploymentNameFromPodName(String podName) {
        String[] elements = podName.split("-");
        StringBuilder sb = new StringBuilder();
        if (elements.length > 2) {
            for (int i = 0; i < elements.length - 2; i++) {
                if (i == elements.length - 3) {
                    sb.append(elements[i]);
                } else {
                    sb.append(elements[i]).append("-");
                }
            }
        } else {
            sb.append(elements[0]);
        }
        return sb.toString();
    }
}
